package com.work.game.utils;


import android.os.Build;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.logging.Logger;

import javax.crypto.Cipher;

public class RSAEncrypt {
    //////////生产//////////////////
    public static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCRBuk3ZAPm/UPwAYwmAUDNpOaCHNGeEnKhrJjp2cJuQyDkc5QvNotx8bJK2B9cO3QrJ6XjGrCLCZXRYpXz3k3veRn03983MnXbS8PHJZhXgco1Ms4VWwgf4MF2P8Q78dyBQ6l1ALAsiVWiLrNhTXAQgooideju73o3JnoOsTom6QIDAQAB";
    private static final Logger logger = Logger.getLogger("RSAEncrypt");

    //参数一：需要加密的文本  参数二:加密的公钥
    public static String encrypt(String text) {
        try {
            // Base64为android util包自带的，publicKeyString是服务器获取的公钥字符串，参数选择NO_WRAP
            byte[] keyByte = android.util.Base64.decode(publicKey.getBytes(), android.util.Base64.NO_WRAP);
            // 获取keyspec （java.security.spec.X509EncodedKeySpec）
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyByte);
            // 获取keyfactory （java.security.KeyFactory）
            KeyFactory keyFactory;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                //适配Android P及以后版本，否则报错NoSuchAlgorithmException
                keyFactory = KeyFactory.getInstance("RSA");
            } else {
                keyFactory = KeyFactory.getInstance("RSA", "BC");
            }
            // 获取公钥 （java.security.PublicKey）
            PublicKey publicKey = keyFactory.generatePublic(keySpec);
            // 初始化加密类
            Cipher cipher = null;
            cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            // 加密后获取字节数组 text为要加密的字符串
            byte[] enBytes = cipher.doFinal(text.getBytes());
            // 加密结果再做一次编码，获取的字符串作为密文传给服务器验证
            return android.util.Base64.encodeToString(enBytes, android.util.Base64.NO_WRAP);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
